package com.boot.weirdor.web.www;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.boot.weirdor.common.exception.BootWeirdorClientException;
import com.boot.weirdor.common.exception.BootWeirdorException;
import com.boot.weirdor.module.entity.User;
import com.boot.weirdor.module.mapper.UserMapper;
import com.boot.weirdor.module.service.IUserService;
import com.boot.weirdor.web.base.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * Created by weirdor on 2017/8/18.
 */
@RestController
@RequestMapping("/api")
public class UserController extends BaseController {


    @Autowired
    private IUserService userService;

    @Autowired
    private UserMapper userMapper;

    /**
     * 新增用户
     *
     * @param users    用户信息
     * @param request
     * @param response
     * @return map
     */

    @RequestMapping(value = "/users", method = RequestMethod.POST)
    public Map<String, Object> create(@RequestBody User users, HttpServletRequest request,
                                      HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            boolean flag = userService.insert(users);
            map.put("status", flag);
            map.put("id", users.getId());
            map.put("message", "user with id '" + users.getId() + "' has been created!");
        } catch (BootWeirdorException e) {
            map.put("code", e.getErrorCode());
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            map.put("message", e.getMessage());
            map.put("data", users);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            map.put("data", users);
            map.put("message", e);
        }
        return map;
    }


    /**
     * 修改用户信息
     *
     * @param id   用户id
     * @param user 修改信息
     */
    @RequestMapping(value = "/users/{id}", method = RequestMethod.PUT)
    public Map<String, Object> update(HttpServletRequest request, HttpServletResponse response,
                                      @RequestBody User user, @PathVariable("id") String id) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            EntityWrapper<User> wrapper = new EntityWrapper<User>();
            wrapper.eq("id", id);
            boolean flag = userService.update(user, wrapper);
            if (flag) {
                map.put("message", id + " items has been updated");
            }
        } catch (BootWeirdorClientException e) {
            map.put("code", e.getErrorCode());
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            map.put("message", e.getMessage());
            map.put("data", user);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            map.put("message", e);
            map.put("data", user);
        }
        return map;
    }

    /**
     * 查询详细信息
     *
     * @param id 用户id
     */
    @RequestMapping(value = "/users/{id}", method = RequestMethod.GET)
    public Object findById(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") String id) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            EntityWrapper<User> wrapper = new EntityWrapper<User>();
            wrapper.eq("id", id);
            List<User> userList = userService.selectList(wrapper);
            if (userList != null) {
                return userList;
            } else {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                map.put("message", "用户【" + id + "】不存在");
            }

        } catch (BootWeirdorClientException ie) {
            map.put("code", ie.getErrorCode());
            map.put("message", ie);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            map.put("message", e);
        }
        return map;
    }

    /**
     * 查询所有用户信息
     *
     * @param pageAble 默认为不分页
     */
    @RequestMapping(value = "/users", method = RequestMethod.GET)
    public Object queryPage(HttpServletRequest request, HttpServletResponse response,
                            @RequestParam(required = false, defaultValue = "{}") String query,
                            @RequestParam(required = false, defaultValue = "false") boolean pageAble,
                            @RequestParam(required = false, defaultValue = "0") int pageNum,
                            @RequestParam(required = false, defaultValue = "20") int size,
                            @RequestParam(required = false, defaultValue = "") String projection) {
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> condition = new HashMap<String, Object>();

        try {
            EntityWrapper<User> wrapper = new EntityWrapper<User>();
            //查询条件
            JSONObject querys = JSON.parseObject(query);
            if (!querys.isEmpty()) {
                Set<String> set = querys.keySet();
                for (String se : set) {
                    if (set.contains(se))
                    wrapper.eq(se,querys.get(se));
                   }
            }
            //判断是否限制返回字段
            if (!StringUtils.isEmpty(projection)) {
                wrapper.setSqlSelect(projection);
            }
            if (pageAble) {
                return  userMapper.selectUserPage(new Page<User>(pageNum,size),condition);
            } else {
                return userService.selectList(wrapper);
            }
        } catch (BootWeirdorClientException ie) {
            map.put("code", ie.getErrorCode());
            map.put("message", ie);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            map.put("message", e);
        }
        return map;
    }

}
